package everyday.leetcode.editor.cn;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: Dang Qi
 * @Date: 2021/3/11  12:43
 * @Description:
 */
public class BasicCalculatorII {

    public static void main(String[] args) {
        Solution solution = new BasicCalculatorII().new Solution();
        String s = "2*3*4";
        System.out.println(solution.calculate(s));


    }
    class Solution {
        public int calculate(String s) {
            Stack<Integer> st = new Stack<>();
            // flag 记录上一个符号 -1 为减号，1 为加号，3 为乘号，4 为除号
            int res = 0, num = 0, flag = 1;

            for(int i = 0; i < s.length(); i++){
                switch(s.charAt(i)){
                    case ' ' :continue;
                    case '-':
                    case '+':
                        if(flag > 2) res = flag==3? res*num : res/num;
                        else res += num * flag;
                        num = 0;
                        flag = s.charAt(i)=='-' ? -1 : 1;
                        break;
                    case '*':
                    case '/':
                        if(flag < 2){
                            st.push(res); res = flag * num;
                        }
                        else res = flag==3? res*num : res/num;
                        num = 0;
                        flag = s.charAt(i)=='*' ? 3 : 4;
                        break;
                    default:
                        num = num * 10 + s.charAt(i) - '0';
                }
            }
            if(flag > 2) res = flag==3? res*num : res/num;
            else res += num * flag;
            while(!st.isEmpty()) res += st.pop();
            return res;
        }
    }
}

